package com.iwhalecloud.uncc.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class MD5Util {

    /**
     * MD5算法
     * @param dataStr
     * @return
     */
    public static String md5Encrypt(String dataStr) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(dataStr.getBytes("UTF8"));
            byte s[] = m.digest();
            String result = "";
            for (int i = 0; i < s.length; i++) {
                result += Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00).substring(6);
            }
            return result;
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return "";
    }

        /*
    * 对输入的字符串进行md5计算，返回计算后的md5字符串
    * */
    public static String[] getMD5Array(String inputString) {
        String[] md5Array = new String[4];
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(inputString.getBytes());
            md5Array = convertBytes(md.digest());
        } catch (NoSuchAlgorithmException e) {
            log.error(ExceptionUtils.getStackTrace(e));
        } catch (UnsupportedEncodingException e) {
            log.error(ExceptionUtils.getStackTrace(e));
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return md5Array;
    }

    public static String getMD5Str(String inputString) {
        String[] md5Array=getMD5Array( inputString);
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<4;i++){
            sb.append(md5Array[i]);
        }
        return sb.toString();
    }

	    
    /*
     * 根据md5的数组,返回md5对应的字符串
     * */
    private static String[] convertBytes(byte[] bytes) throws Exception {
        String[] strArray = new String[4];

        if (bytes.length != 16) {
			throw new Exception("MD5长度不合法");
		} else {
            for (int i = 0; i < 4; i++) {
                long fp = (long) Math.pow(2, 24) * (bytes[i * 4] & 0xFF) +
                        (long) Math.pow(2, 16) * (bytes[i * 4 + 1] & 0xFF) +
                        (long) Math.pow(2, 8) * (bytes[i * 4 + 2] & 0xFF) +
                        (bytes[i * 4 + 3] & 0xFF);
                strArray[i] = Long.toString(fp);
            }
        }
        return strArray;
    }


	public static String getString(String str) {
        if (str == null) {
			str = "null";
		}
        String[] strs = getMD5Array(str);
        return strs[0] + strs[1] + strs[2] + strs[3];
    }

}